package com.zktravel.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class CommonHelper {
	protected static Logger logger = LoggerFactory.getLogger(CommonHelper.class);

	/**
	 * 持有额外的验证消息
	 */
	private final static ThreadLocal<String> VALID_EXTRA_MSG_HOLDER = new InheritableThreadLocal<>();
	/**
	 * 持有错误消息
	 */
	private final static ThreadLocal<String> ERROR_HOLDER = new InheritableThreadLocal<>();

	private final static String[] MODEL_SUFFIXES = new String[]{"DTO", "PO", "VO", "SO", "Mapper"};
	private final static char[] RANDOM_CHARS = new char[] {
			'!', '"', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/',
			'1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '?', '@',
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_',
			'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '~'
	};

	public static void setValidExtraMsg(String msg) {
		VALID_EXTRA_MSG_HOLDER.set(msg);
	}

	public static String getValidExtraMsg() {
		String msg = VALID_EXTRA_MSG_HOLDER.get();
		VALID_EXTRA_MSG_HOLDER.remove();
		return msg;
	}

	public static void setMsgOnErr(String errmsg) {
		ERROR_HOLDER.set(errmsg);
	}

	public static String getMsgOnErr() {
		String errmsg = ERROR_HOLDER.get();
		ERROR_HOLDER.remove();
		return errmsg;
	}


	public static String getModelName(String name) {
		for (String suffix : MODEL_SUFFIXES) {
			if (name.endsWith(suffix)) return name.substring(0, name.length() - suffix.length());
		}
		return name;
	}

	public static String generateRandomCode(int length) {
		char[] chars = RANDOM_CHARS;
		char[] rslt = new char[length];
		Random random = new Random();
		for (int i=0; i<length; i++) {
			int idx = random.nextInt(chars.length);
			rslt[i] = chars[idx];
		}
		return new String(rslt);
	}

	/**
	 * 使用序列化的方式深拷贝
	 * @param src
	 * @param <T>
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static <T> List<T> copy(List<T> src) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(byteOut);
		out. writeObject(src);
		ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		@SuppressWarnings("unchecked")
		List<T> dest = (List<T>) in.readObject();
		return dest;
	}

	public static boolean isTrue(Integer boolValue) {
		if (boolValue == null) return false;
		return Integer.valueOf(1).equals(boolValue);
	}
}
